package com.ljh.localmusic.foundation.media_player

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.session.MediaSession
import androidx.media3.session.MediaSessionService
import androidx.media3.ui.PlayerNotificationManager
import com.ljh.localmusic.R
import com.ljh.localmusic.runtime.App
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

object Constants{
    const val NOTIFICATION_ID = 888
    const val NOTIFICATION_CHANNEL_NAME = "music notification channel 888"
    const val NOTIFICATION_CHANNEL_ID = "music notification channel id 888"
}

class MusicNotificationManager @Inject constructor(
    private val exoPlayer: Player
) {
    private val musicNotificationManager by lazy {
        NotificationManagerCompat.from(App.app)
    }

    init {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            createMusicNotificationChannel()
        }
    }

    /**
     * 1. 创建通知渠道（Android 8.0+）
     */
    private fun createMusicNotificationChannel(){

        val musicNotificationChannel = NotificationChannel(
            Constants.NOTIFICATION_CHANNEL_ID,
            Constants.NOTIFICATION_CHANNEL_NAME,
            NotificationManager.IMPORTANCE_DEFAULT
        )
        musicNotificationManager.createNotificationChannel(musicNotificationChannel)
    }


    private fun buildMusicNotification(mediaSession:MediaSession){
        PlayerNotificationManager.Builder(
            App.app,
            Constants.NOTIFICATION_ID,
            Constants.NOTIFICATION_CHANNEL_ID
        )
            .setMediaDescriptionAdapter(
                object : PlayerNotificationManager.MediaDescriptionAdapter{
                    override fun getCurrentContentTitle(player: Player): CharSequence = player.mediaMetadata.albumTitle ?: "Unknown"

                    override fun createCurrentContentIntent(player: Player): PendingIntent? = mediaSession.sessionActivity

                    override fun getCurrentContentText(player: Player): CharSequence? = player.mediaMetadata.displayTitle ?: "Unknown"

                    override fun getCurrentLargeIcon(
                        player: Player,
                        callback: PlayerNotificationManager.BitmapCallback
                    ): Bitmap? {
                        // 获取媒体元数据中的封面 URI
                        val artworkUri = player.mediaMetadata.artworkUri
                            ?: // 无封面 URI 时返回默认图标
                            return BitmapFactory.decodeResource(
                                App.app.resources,
                                R.drawable.ic_launcher_foreground // 替换为你的默认封面
                            )

                        // 异步加载图片（避免阻塞主线程）
                        loadBitmapAsync(artworkUri) { bitmap ->
                            // 关键：如果 bitmap 为 null，用默认图兜底（确保非空）
                            val nonNullBitmap = bitmap ?: BitmapFactory.decodeResource(
                                App.app.resources,
                                R.drawable.ic_launcher_foreground
                            )
                            // 通过 callback 返回加载好的 bitmap
                            callback.onBitmap(nonNullBitmap)
                        }

                        // 暂时返回 null，等待异步加载完成后通过 callback 更新
                        return null
                    }
                }
            )
            .setSmallIconResourceId(R.drawable.ic_launcher_foreground)
            .build()
            .also {
                it.setMediaSessionToken(mediaSession.platformToken)
                it.setUseFastForwardActionInCompactView(true)
                it.setUseRewindActionInCompactView(true)
                it.setUseNextActionInCompactView(true)
                it.setUsePreviousActionInCompactView(true)
                it.setPriority(NotificationCompat.PRIORITY_DEFAULT)
                it.setPlayer(exoPlayer)
            }
    }


    fun startMusicNotificationService(
        mediaSessionService: MediaSessionService,
        mediaSession: MediaSession
    ){
        buildMusicNotification(mediaSession)
        startForegroundMusicService(mediaSessionService)
    }

    private fun startForegroundMusicService(mediaSessionService: MediaSessionService){
        val musicNotification = Notification.Builder(App.app,Constants.NOTIFICATION_CHANNEL_ID)
            .setCategory(Notification.CATEGORY_SERVICE)
            .build()

        mediaSessionService.startForeground(Constants.NOTIFICATION_ID,musicNotification)
    }
}

// 异步加载图片的工具方法
private fun loadBitmapAsync(uri: Uri, onLoaded: (Bitmap?) -> Unit) {
    // 使用后台线程加载图片
    CoroutineScope(Dispatchers.IO).launch {
        val bitmap = try {
            // 通过 ContentResolver 从 URI 加载图片
            App.app.contentResolver.openInputStream(uri)?.use { inputStream ->
                // 压缩图片避免内存溢出
                val options = BitmapFactory.Options().apply {
                    inSampleSize = 2 // 缩小为原来的 1/2（根据需求调整）
                    inPreferredConfig = Bitmap.Config.RGB_565 // 降低色彩深度
                }
                BitmapFactory.decodeStream(inputStream, null, options)
            }
        } catch (e: Exception) {
            // 处理加载失败（如 URI 无效、权限问题）
            e.printStackTrace()
            null
        }

        // 切换到主线程回调结果
        withContext(Dispatchers.Main) {
            onLoaded(bitmap ?: BitmapFactory.decodeResource(
                App.app.resources,
                R.drawable.ic_launcher_foreground // 加载失败时显示默认封面
            ))
        }
    }
}


